package com.calvin.android;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import android.app.Activity;
import android.view.View;
import android.view.ViewGroup.LayoutParams;

import com.calvin.android.EventDispatch.CListen;
import com.calvin.android.annotation.ViewInject;
import com.calvin.android.notification.NotificationCenter;

public abstract class CActivity extends Activity {
	private static CActivity mCurrentInstance = null;

	public CActivity() {
		super();
		mCurrentInstance = this;
	}

	public static CActivity sharedCurrent() {
		return mCurrentInstance;
	}

	@Override
	public void setContentView(View view, LayoutParams params) {
		super.setContentView(view, params);
		CActivity.initViewInject(this, getWindow().getDecorView());
	}

	@Override
	public void setContentView(int layoutResID) {
		super.setContentView(layoutResID);
		CActivity.initViewInject(this, getWindow().getDecorView());
	}

	@Override
	public void setContentView(View view) {
		super.setContentView(view);
		CActivity.initViewInject(this, getWindow().getDecorView());
	}

	public <T> T cast(Class<T> clazz) {
		return clazz != null && clazz.isInstance(this) ? clazz.cast(this) : null;
	}

	public static void initViewInject(Activity activity) {
		if (null != activity) {
			initViewInject(activity, activity.getWindow().getDecorView());
		}
	}

	public static void initViewInject(Object target, View view) {
		if (null != view || null != target) {
			Field[] fields = target.getClass().getDeclaredFields();
			View subView = null;
			for (Field field : fields) {
				ViewInject inject = field.getAnnotation(ViewInject.class);
				if (inject != null && (subView = inject.isTag() ? view.findViewWithTag(inject.tag()[0]) : view.findViewById(inject.id()[0])) != null) {
					try {
						field.setAccessible(true);
						field.set(target, subView);
					} catch (Exception e) {
					}
				}
			}
			Method[] methods = target.getClass().getMethods();
			for (Method method : methods) {
				ViewInject inject = method.getAnnotation(ViewInject.class);
				if (inject != null && inject.isTag() && inject.tag().length > 0) {
					for (String tag : inject.tag()) {
						if ((subView = view.findViewWithTag(tag)) != null) {
							for (CListen listent : inject.listen()) {
								EventDispatch.shared().put(subView, listent, target, method.getName());
							}
						}
					}
				} else if (inject != null && !inject.isTag() && inject.id().length > 0) {
					for (int id : inject.id()) {
						if ((subView = view.findViewById(id)) != null) {
							for (CListen listent : inject.listen()) {
								EventDispatch.shared().put(subView, listent, target, method.getName());
							}
						}
					}
				}
			}
		}
	}

	public static void scanNotice(Object object) {
		NotificationCenter.shared().scanNotice(object);
	}
}
